package com.yr.ryjk.jpush;

import java.util.Map;

import org.apache.log4j.Logger;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.APIConnectionException;
import cn.jpush.api.common.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.Notification;

import com.yr.ryjk.common.Constant;

public class JpushSendService {
	private static JPushClient jPushClient = null;
	private static Logger logger = Logger.getLogger(JpushSendService.class);
	static{
		jPushClient = new JPushClient(Constant.master_secret, Constant.app_key);
	}

	/**
	 * 推送android，通知类
	 * 
	 * @param title 
	 * @param content
	 * @param customerFields
	 * @param registerIds 极光推送的id数组，最大1000个
	 */
	public  static void sendAndroidNotice(JpushMessage msg, Map<String, String> customerFields, String... registerIds) {
		_isRegisterIdsValid(registerIds);
		PushPayload payload = PushPayload.newBuilder().
						setPlatform(Platform.android()).
						setAudience(Audience.registrationId(registerIds)).
						setNotification(Notification.newBuilder().
								addPlatformNotification(AndroidNotification.newBuilder().
											setTitle(msg.getTitle()).
											setAlert(msg.getContent()).
											setBuilderId(1).
											build()).
								build()).
						build();
		if(_sendAndroid(payload)){
			logger.info("安卓通知发送成功：title=" + msg.getTitle() + ";content=" + msg.getContent() + ";目标" );
		}else{
			logger.error("安卓通知发送失败：title=" + msg.getTitle() + ";content=" + msg.getContent() + ";目标" );
		}
	}
	
	/**
	 * 推送android，透传消息类
	 * 
	 * @param content
	 * @param registerIds 极光推送的id数组，最大1000个
	 */
	public static void sendAndroidMessage(String content, String... registerIds) {
		_isRegisterIdsValid(registerIds);
		
		PushPayload payload = PushPayload.newBuilder().
				setPlatform(Platform.android()).
				setAudience(Audience.registrationId(registerIds)).
				setMessage(Message.content(content)).
				build();
		if(_sendAndroid(payload)){
			logger.info("安卓消息发送成功：content=" + content + ";目标" );
		}else{
			logger.error("安卓消息发送失败：content=" + content + ";目标" );
		}
	}
	
	private static void _isRegisterIdsValid(String... registerIds){
		if (registerIds == null || registerIds.length == 0 || registerIds.length >= 1000){
			throw new RuntimeException("安卓推送目标id设置错误，为空或者大于1000个");
		}
	}

	private static boolean _sendAndroid(PushPayload payload){
		try {
			PushResult result = jPushClient.sendPush(payload);

			return result.isResultOK();
		}catch (APIConnectionException e) {
			logger.error("Connection error. Should retry later. ", e);
		} catch (APIRequestException e){
			logger.info("HTTP Status: " + e.getStatus());
			logger.info("Error Code: " + e.getErrorCode());
			logger.info("Error Message: " + e.getErrorMessage());
			logger.info("Msg ID: " + e.getMsgId());
		}
		
		return false;
	}
//	
//	public static void main(String[] args) {
//		JpushSendService pushSendService = new JpushSendService();
//		JpushMessage msg = new JpushMessage();
//		User user = new User();
//		user.setPhone("18321948716");
//		JedisUtil.putPhoneJPushMap(user.getPhone(), "050202b2ad4");
//		String jpDevice  = JedisUtil.getJPushKeyByPhone(user.getPhone());
//		System.out.println(jpDevice);
//		System.exit(0);
//		msg.setTitle("cesho");
//		msg.setContent("打击好");
//		msg.setConsultId("1");
//		msg.setType("1");
//		msg.setTitle("ceshi");
//		msg.setName("taiyangshen");
//		
//
//		String jpushMap =  JSONObject.toJSON(msg).toString();
//		pushSendService.sendAndroidMessage(jpushMap, new String[]{jpDevice});//透传 // /090f530e8d6
////		pushSendService.sendAndroidNotice(msg.getTitle(), msg.getContent(), new HashMap(), new String[]{"050202b2ad4"});//发送健康币
//	}
}
